package com.itheima.web;

import com.itheima.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Controller
public class FileController {
    @Value("${fileDir}")
    private String fileDir;

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/common/upload")
    @ResponseBody
    public R upload(MultipartFile file) throws IOException {
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;

        File dir = new File(fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        file.transferTo(new File(dir +"/"+ fileName));
        return R.success(fileName);
    }

    @GetMapping("/common/download")
    public void download(String name, HttpServletResponse resp) throws Exception {
        FileInputStream fis = new FileInputStream(new File(fileDir + "/"+name));
        ServletOutputStream os = resp.getOutputStream();

        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len=fis.read(buffer))!=-1){
            os.write(buffer,0,len);
        }

        fis.close();
        os.close();
    }
}
